/*
 * Copyright (c) 2020-2021. the original authors and DEPSEA.ORG
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.depsea.log.handler;

import lombok.extern.slf4j.Slf4j;
import org.depsea.log.config.properties.LogPointAspectProperties;
import org.depsea.log.model.RequestInfo;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 *
 * @author jaune
 * @since 1.0.0
 */
@Slf4j
public class ElasticsearchRequestPointHandler implements RequestPointHandler {

    private final ElasticsearchRestTemplate elasticsearchRestTemplate;

    private final LogPointAspectProperties logPointAspectProperties;

    public ElasticsearchRequestPointHandler(ElasticsearchRestTemplate elasticsearchRestTemplate, LogPointAspectProperties logPointAspectProperties) {
        this.elasticsearchRestTemplate = elasticsearchRestTemplate;
        this.logPointAspectProperties = logPointAspectProperties;
    }

    @Override
    public boolean isAsync() {
        return true;
    }

    @Override
    public void handle(RequestInfo requestInfo) {
        String indexName = this.logPointAspectProperties.getRequestLogIndexNamePrefix() + "-"
                + LocalDate.now().format(DateTimeFormatter.ofPattern(this.logPointAspectProperties.getDatePattern()));
        log.debug("Write request info to {}", indexName);
        IndexCoordinates indexCoordinates = IndexCoordinates.of(indexName);
        this.elasticsearchRestTemplate.save(requestInfo, indexCoordinates);
    }

}
